package cn.com.dbappsecurity.frame.handler;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import cn.com.dbappsecurity.frame.Constant;
import cn.com.dbappsecurity.frame.datamodal.JsonDataModal;

/**
 * 用户登录检查处理器
 * @author dhz
 */
public class LoginHandler{

	private static final Logger LOG = Logger.getLogger(LoginHandler.class);
	
	/**
	 * 登录页地址，未登录则跳转至该页
	 */
	public static final String LOGIN_PAGE = "login.jhtml";
	/**
	 * 额外不检查登录的请求，多个间用逗号隔开
	 */
	public static final String[] UNSESSION = {"user.login.jx","user.logout.jx","login.jhtml"};
	
	public boolean execute(HttpServletRequest request,HttpServletResponse response){
		if(isSessionOut(request)){
			//ajax请求
			if(isAjaxRequest(request)){
				JsonDataModal modal = new JsonDataModal(false);
				modal.putObj("sessionout",true);
				modal.shipToResponse(request, response);
			}
			//页面请求,可能存在iframe嵌套，这里用JS跳转
			else{
				String loginUri = request.getContextPath();
				if(!LOGIN_PAGE.startsWith("/")){
					loginUri += "/";
				}
				loginUri += LOGIN_PAGE;
				try {
					response.getWriter().write("<script type=\"text/javascript\">window.top.location.href='"+loginUri+"';</script>");
				} catch (IOException e) {
					LOG.error("响应内容出错",e);
				}
			}
			return false;
		}
		return true;
	}
	

	/*
	 * 是否登录超时
	 * @param req
	 * @return
	 */
	private boolean isSessionOut(HttpServletRequest req){
		String uri = req.getRequestURI();
		String context = req.getContextPath();
		uri = uri.substring(context.length());
		
		boolean sessionout = true;
		HttpSession session = req.getSession();
		if(session.getAttribute(Constant.AUTH_KEY) != null || uri.equals(LOGIN_PAGE)){
			sessionout = false;
		}else if(UNSESSION != null){
			for(String pg : UNSESSION){
				if(!pg.startsWith("/")){
					pg = "/" + pg;
				}
				if(uri.equals(pg)){
					sessionout = false;
					break;
				}
			}
		}
		return sessionout;
	}
	
	/*
	 * 判断是否为ajax请求
	 * @param request
	 * @return
	 */
	private boolean isAjaxRequest(HttpServletRequest request) {
		return request.getRequestURI().endsWith(Constant.CONTROLLER_SUFFIX);
		/*String header = request.getHeader("X-Requested-With");
		return header != null && "XMLHttpRequest".equals(header);*/
	}

}
